package com.gict.antifraudback.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.HashMap;
import java.util.Map;

/**
 * 爬虫工具类
 */
public class JsoupUtil {

    private static final Logger logger = LoggerFactory.getLogger(JsoupUtil.class);

    private static final Map<String,String> headers = new HashMap<>();

    private static final Integer timeOut = 10000;

    private static final Proxy PROXY;

    static {
        PROXY = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 33210));
        headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
        headers.put("Accept-Encoding", "gzip, deflate, br, zstd");
        headers.put("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0");
    }

    public static Document sendGet(String url){
        try {
            return Jsoup.connect(url).timeout(timeOut)
                    .proxy(PROXY)
                    .headers(headers)
                    .header("Referer", "https://cdn.btlm.top:65533/s?word=985469")
                    .get();
        } catch (IOException e) {
            logger.error("请求发送错误url:{}, message:{}", url, e.getMessage());
            return null;
        }
    }

    public static Document sendPost(String url, Map<String, String> map){
        try {
            return Jsoup.connect(url).timeout(timeOut).ignoreContentType(true)
                    .headers(headers)
                    .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                    .data(map)
                    .post();
        } catch (IOException e) {
            logger.error("请求发送错误url:{}, message:{}", url, e.getMessage());
            return null;
        }
    }

    public static Document sendPostByBody(String url, String json){
        try {
            return Jsoup.connect(url).timeout(timeOut).ignoreContentType(true)
                    .headers(headers)
                    .header("Content-Type", "application/json;charset=utf-8")
                    .requestBody(json)
                    .post();
        } catch (IOException e) {
            logger.error("请求发送错误url:{}, message:{}", url, e.getMessage());
            return null;
        }
    }
}
 